package com.mnt.washio.activities;

import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.HttpMethod;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.model.GraphObject;
import com.facebook.model.GraphUser;
import com.mnt.washio.R;
import com.mnt.washio.utils.Statics;
import com.mnt.washio.views.CongraDialog;
import com.parse.ParseException;
import com.parse.ParseUser;
import com.parse.SaveCallback;
import com.parse.SignUpCallback;

public class RegisterActivity extends BaseActivityNoTitle implements
		OnClickListener {
	private Button myButtonRegister;
	private EditText mEdtEmail, mEdtPassword, mEdtFirstName, mEdtLastName,
			mEdtPhone;
	private ProgressDialog pd;

	@Override
	public void initViews() {
		// TODO Auto-generated method stub
		((TextView) findViewById(R.id.tv_title_bar))
				.setText(R.string.txt_register);
		pd = new ProgressDialog(this);
		pd.setCancelable(false);

		mEdtEmail = (EditText) findViewById(R.id.edt_email);
		mEdtPassword = (EditText) findViewById(R.id.edt_password);
		mEdtFirstName = (EditText) findViewById(R.id.edt_first_name);
		mEdtLastName = (EditText) findViewById(R.id.edt_last_name);
		mEdtPhone = (EditText) findViewById(R.id.edt_phone);

		ParseUser user = ParseUser.getCurrentUser();
		if (user.getObjectId() != null && user.getEmail() == null) {
			if (Session.getActiveSession().isOpened()) {
				pd.setMessage("Loading...");
				pd.show();

				Request request = Request.newMeRequest(
						Session.getActiveSession(),
						new Request.GraphUserCallback() {
							@Override
							public void onCompleted(GraphUser user,
									Response response) {
								// If the response is successful
								if (user != null) {
									getFaceAccInfo(user.getId());

								}
							}
						});

				Request.executeBatchAsync(request);
			}
		}

		myButtonRegister = (Button) findViewById(R.id.btn_register);
		initProperties();
		addListener();
	}

	private void getFaceAccInfo(String userId) {
		if (!pd.isShowing())
			pd.show();
		String fqlQuery = "SELECT uid,first_name,last_name,email "
				+ "FROM user WHERE uid='" + userId + "'";
		Bundle params = new Bundle();
		params.putString("q", fqlQuery);
		Session session = Session.getActiveSession();
		Request request = new Request(session, "/fql", params, HttpMethod.GET,
				new Request.Callback() {
					public void onCompleted(Response response) {
						pd.dismiss();
						try {
							GraphObject graphObject = response.getGraphObject();
							JSONObject jsonObject = graphObject
									.getInnerJSONObject().getJSONArray("data")
									.getJSONObject(0);
							mEdtFirstName.setText(jsonObject
									.getString("first_name"));
							mEdtLastName.setText(jsonObject
									.getString("last_name"));
							mEdtEmail.setText(jsonObject.getString("email"));
						} catch (Exception e) {
						}

					}
				});
		Request.executeBatchAsync(request);
	}

	@Override
	public int getContentView() {
		// TODO Auto-generated method stub
		return R.layout.fragment_register;
	}

	@Override
	public void initProperties() {
		// TODO Auto-generated method stub

	}

	public void addListener() {
		// TODO Auto-generated method stub
		myButtonRegister.setOnClickListener(this);
	}

	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.imv_menu:
			finish();
			break;
		case R.id.btn_register:
			validateAndRegister();

			break;
		default:
			break;
		}
	}

	private void validateAndRegister() {
		String username = mEdtEmail.getText().toString().trim();
		if (username.length() == 0) {
			Statics.showToast(this, "Email is required");
			return;
		}

		if (!Statics.isEmailValid(username)) {
			Statics.showToast(this, "Email is invalid");
			return;
		}

		String password = mEdtPassword.getText().toString().trim();
		if (password.length() == 0) {
			Statics.showToast(this, "Password is required");
			return;
		}
		ParseUser user;
		if (ParseUser.getCurrentUser().getObjectId() != null) {
			user = ParseUser.getCurrentUser();
		} else {
			user = new ParseUser();
		}
		user.setUsername(username);
		user.setPassword(password);
		user.setEmail(username);
		user.put("first_name", mEdtFirstName.getText().toString().trim());
		user.put("last_name", mEdtLastName.getText().toString().trim());
		user.put("phone", mEdtPhone.getText().toString().trim());

		// Call the asynchronous background method to sign up
		pd.setMessage("Registering...");
		pd.show();
		if (ParseUser.getCurrentUser().getObjectId() != null) {
			user.saveInBackground(new SaveCallback() {

				@Override
				public void done(ParseException e) {
					pd.dismiss();
					if (e == null) {
						new CongraDialog(RegisterActivity.this,
								CongraDialog.ACCOUNT) {
							public void onDissmis() {
								Intent i = new Intent(RegisterActivity.this,
										RegisterStep2Activity.class);
								i.putExtra("REGISTER", true);
								startActivity(i);
								
								finish();
							};
						}.show();

					} else {
						Toast.makeText(RegisterActivity.this,
								"Register fail: " + e.getMessage(),
								Toast.LENGTH_SHORT).show();
					}
				}
			});
		} else {

			user.signUpInBackground(new SignUpCallback() {

				public void done(ParseException e) {
					pd.dismiss();
					if (e == null) {
						Toast.makeText(RegisterActivity.this,
								"Register Successfully", Toast.LENGTH_SHORT)
								.show();
						Intent i = new Intent(RegisterActivity.this,
								RegisterStep2Activity.class);
						i.putExtra("REGISTER", true);
						startActivity(i);
						finish();
					} else {
						Toast.makeText(RegisterActivity.this,
								"Register fail: " + e.getMessage(),
								Toast.LENGTH_SHORT).show();
					}
				}
			});
		}
	}

}
